from rest_framework import viewsets, parsers
from django_filters import rest_framework as filters
from rest_framework_simplejwt.authentication import JWTAuthentication  # 导入JWT认证类
from django.db.models import Q

# 从当前目录下导入Article模型和ArticleListSerializer序列化器
from .models import Book, Article, Category
from .serializers import BookSerializer, ArticleSerializer, CategorySerializer
from .permissions import IsAdminUserOrReadOnly, IsOwnerOrAdmin


# Create your views here.
# 定义书籍过滤器集
class BookFilter(filters.FilterSet):
    name = filters.CharFilter(lookup_expr='icontains')
    category_id = filters.NumberFilter(field_name='category')


    class Meta:
        model = Book
        fields = ['name', "category_id"]


# 定义书籍视图集
class BookViewSet(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = BookFilter  # 使用BookFilter来应用过滤
    
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsOwnerOrAdmin | IsAdminUserOrReadOnly]  # 允许所有者或管理员修改
    parser_classes = [parsers.MultiPartParser, parsers.FormParser, parsers.JSONParser] # 在视图级别指定parser_classes以支持文件上传

    def perform_create(self, serializer):
        # 自动关联上传用户
        if self.request.user.is_authenticated:
            profile = self.request.user.profile
            instance = serializer.save()
            instance.owning_profiles.add(profile)
        else:
            serializer.save()

    def get_queryset(self):
        queryset = Book.objects.all()
        
        # 先应用过滤条件
        user = self.request.user
        
        # 再应用权限过滤
        if user.is_staff:
            # 管理员可查看所有书籍
            pass
        elif user.is_authenticated:
            # 认证用户：自己的书籍 + 已发布的书籍
            queryset = queryset.filter(
                Q(owning_profiles__user=user) | Q(is_published=True))
        else:
            # 游客：仅已发布书籍
            queryset = queryset.filter(is_published=True)
        
        # 应用django-filter的过滤条件（关键修复）
        queryset = self.filter_queryset(queryset)  # 手动调用过滤方法
        
        return queryset.distinct()  # 最终返回经过权限和django-filter双重过滤的结果

    def get_serializer_context(self):
        # 为序列化器提供request上下文
        context = super().get_serializer_context()
        context.update({'request': self.request})
        return context


# 定义文章视图集
class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    pagination_class = None  # 禁用分页
    serializer_class = ArticleSerializer
    # permission_classes = [IsAdminUserOrReadOnly]
    filter_backends = [filters.DjangoFilterBackend]  # 新增过滤后端
    filterset_fields = ['book']  # 新增可过滤字段


# 定义分类视图集
class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUserOrReadOnly]